package utils

import (
    "encoding/binary"
    "encoding/json"
    "fmt"
    "gitee.com/HyoJoo-W/ChatRoom/common/message"
    "net"
)

// Transfer 将方法封装到结构体中
type Transfer struct {
    Conn net.Conn
    Buf  [8096]byte //传输时,使用缓存
}

// ReadPkg 读取客户端发送的消息
func (this *Transfer) ReadPkg() (msg message.Message, err error) {
    fmt.Println("正在读取客户端发送的数据...")
    _, err = this.Conn.Read(this.Buf[:4])
    if err != nil {
        fmt.Println("读取客户端发送的消息失败, err=", err)
        // err = errors.New("read pkg header error")
        return
    }
    // fmt.Println("读到的buf为：", buf[:4])
    //根据buf[:4]转换为uint32类型
    var pkgLen = binary.BigEndian.Uint32(this.Buf[:4])
    //根据pkgLen读取消息内容
    var n int
    n, err = this.Conn.Read(this.Buf[:pkgLen])
    if n != int(pkgLen) || err != nil {
        fmt.Println("conn.Read err = ", err)
        // err = errors.New("read pkg body error")
        return
    }
    //将pkgLen反序列化->message.Message
    err = json.Unmarshal(this.Buf[:pkgLen], &msg)
    if err != nil {
        fmt.Println("json.Unmarshal err =", err)
        return
    }
    return
}

// WritePkg 给客户端发送响应
func (this *Transfer) WritePkg(data []byte) (err error) {
    //1 先发送一个长度给客户端
    var pkgLen = uint32(len(data))

    binary.BigEndian.PutUint32(this.Buf[0:4], pkgLen)

    //发送长度
    n, err := this.Conn.Write(this.Buf[:4])
    if n != 4 || err != nil {
        fmt.Println("conn.Write(bytes) err= ", err)
        return
    }

    //2 发送消息
    n, err = this.Conn.Write(data)
    if n != int(pkgLen) || err != nil {
        fmt.Println("conn.Write err = ", err)
        return
    }
    return
}
